import cv2
import numpy as np
import os
# 边缘检测
filename = os.path.abspath('第二次作业/lena.jpg') 
lena = cv2.imread(filename)
# cv2.CV_64F为深度，表示可以取负值
sobelImgx = cv2.Sobel(lena,cv2.CV_64F,1,0,ksize=3)
sobelImgy = cv2.Sobel(lena,cv2.CV_64F,0,1,ksize=3)
sobelImgxy = cv2.Sobel(lena,-1,1,1,ksize=3)
cv2.imshow('original',lena)
cv2.imshow('sobelImgx',sobelImgx)
cv2.imshow('sobelImgy',sobelImgy)
cv2.imshow('sobelImgxy',sobelImgxy)

# Canny检测
# image：源图像
# threshold1：阈值1
# threshold2：阈值2
# apertureSize：可选参数，Sobel算子的大小
# 其中，较大的阈值2用于检测图像中明显的边缘，但一般情况下检测的效果不会那么完美
# 边缘检测出来是断断续续的。所以这时候用较小的第一个阈值用于将这些间断的边缘连接起来。
# 函数返回的是二值图，包含检测出的边缘
cannyImg1 = cv2.Canny(lena,22,222)
cv2.imshow('cannyImg1',cannyImg1)
cannyImg2 = cv2.Canny(lena,222,222)
cv2.imshow('cannyImg2',cannyImg2)


# 实现robert，Sobel和LOG边缘提取
gray = cv2.imread(os.path.abspath('第二次作业/bear.jpg'),0)
gray = cv2.cvtColor(lena,cv2.COLOR_BGR2GRAY)
w,h = gray.shape
robert_img = np.empty((w,h))
sobel_img = np.empty((w,h))
log_img = np.empty((w,h))
robertx,roberty = np.array([-1,-1,1,1]),np.array([0,1,-1,0])
sobel = np.array([1,0,-1,2,0,-2,1,0,-1])
LOG = np.array([-2,-4,-4,-4,-2,-4,0,8,0,-4,-4,8,24,8,-4,-4,0,8,0,-4,-2,-4,-4,-4,-2])
for i in range(w-2):
    for j in range(h-2):
        origin1 = np.array(gray[i:i+2,j:j+2]).flatten()
        origin2 = np.array(gray[i:i+3,j:j+3]).flatten()
        origin3 = np.array(gray[i:i+5,j:j+5]).flatten()
        robert_img[i][j] = abs(origin1.dot(robertx))
        sobel_img[i][j] = origin2.dot(sobel)
        if(i<w-4 and j<h-4):
            log_img[i][j] = origin3.dot(LOG)

r_sunnzi = [[-1,-1],[1,1]]
list_robert = np.empty((w,h))
for x in range(w):
    for y in range(h):
        if (y + 2 <= h) and (x + 2 <= w):
            imgChild = gray[x:x+2, y:y+2]
            value = r_sunnzi*imgChild
            list_robert[x, y] = abs(value.sum())  

cv2.imshow('origin',gray)
cv2.imshow('robert',list_robert)
cv2.imshow('sobel',sobel_img)
cv2.imshow('LOG',log_img)
cv2.imshow('sobelopen',cv2.Sobel(gray,cv2.CV_64F,1,0,ksize=3))


cv2.waitKey()
cv2.destroyAllWindows()
